package com.yf.httpclient;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText et_username;
	private EditText et_password;
	private Button btn_login;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);

		btn_login = (Button) findViewById(R.id.btn_login);
		btn_login.setOnClickListener(new LoginOnClickListener());

	}

	private class LoginOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			
			new Thread(new Runnable() {

				@Override
				public void run() {
					String path = "http://10.0.3.2:8780/login-demo/login2";
					String username = et_username.getText().toString().trim();
					String password = et_password.getText().toString().trim();
					BasicNameValuePair vp_username = new BasicNameValuePair("username", username);
					BasicNameValuePair vp_password = new BasicNameValuePair("password", password);
					ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
					params.add(vp_username);
					params.add(vp_password);
					DefaultHttpClient httpClient = new DefaultHttpClient();
					
					try {
						UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
						HttpPost request = new HttpPost(path);
						request.setEntity(entity);
						HttpResponse response = httpClient.execute(request);
						int code = response.getStatusLine().getStatusCode();
						
						if (code == 200) {
							InputStream is = response.getEntity().getContent();
							String result = StringUtil.fromStream(is);
							
							showToast(result);
						} else {
							showToast("服务器返回异常");
						}
					} catch (Exception e) {
						e.printStackTrace();
						showToast("网络异常");
					} 
				}
				
			});
		}
	}

	private void showToast(final String msg) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
			}
		});
	}
}
